package com.zerui.manager.app.accessauthorization.executer;

import com.alibaba.cola.catchlog.CatchAndLog;
import com.alibaba.cola.exception.BizException;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.zerui.cola.dto.Response;
import com.zerui.manager.accessauthorization.AccessAuth;
import com.zerui.manager.accessauthorization.domainservice.AccessAuthRepository;
import com.zerui.manager.web.cmd.AccessAuthUpdateCmd;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author wh
 * @create_time 2023-08-23 10:21
 */
@Component
@CatchAndLog
public class AccessAuthUpdateCmdExe {

	@Resource
	private AccessAuthRepository accessAuthRepository;

	public Response execute(AccessAuthUpdateCmd accessAuthUpdateCmd) {

		checkTime(accessAuthUpdateCmd);

		AccessAuth accessAuth = accessAuthRepository.selectById(accessAuthUpdateCmd.getId());
		if(ObjectUtils.isEmpty(accessAuth)){
			throw new BizException("门禁授权不存在");
		}
		AccessAuth accessAuthCmd = AccessAuth.builder()
				.id(accessAuthUpdateCmd.getId())
				.name(accessAuthUpdateCmd.getName())
				.dateType(accessAuthUpdateCmd.getDateType())
				.endDate(accessAuthUpdateCmd.getEndDate())
				.endTime(accessAuthUpdateCmd.getEndTime())
				.remark(accessAuthUpdateCmd.getRemark())
				.startDate(accessAuthUpdateCmd.getStartDate())
				.timeType(accessAuthUpdateCmd.getTimeType())
				.startTime(accessAuthUpdateCmd.getStartTime())
				.createTime(accessAuth.getCreateTime())
				.build();
		//判断日期时间是否变更 - 如果变更需要更新下发
		checkAccessAuthDateTime(accessAuthCmd,accessAuth);
		return accessAuthRepository.update(accessAuthCmd);
	}

	private void checkTime(AccessAuthUpdateCmd accessAuthUpdateCmd) {
		if(accessAuthUpdateCmd.getDateType()>0){
			if(ObjectUtils.isEmpty(accessAuthUpdateCmd.getStartDate()) ||
					ObjectUtils.isEmpty(accessAuthUpdateCmd.getEndDate())
			){
				throw new BizException("开始日期或者结束日期不能为空");
			}

			if(accessAuthUpdateCmd.getStartDate().isAfter(accessAuthUpdateCmd.getEndDate())){
				throw new BizException("日期开始必须在结束之前");
			}
		}

		if(accessAuthUpdateCmd.getTimeType()>0){
			if(
					ObjectUtils.isEmpty(accessAuthUpdateCmd.getStartTime()) ||
							ObjectUtils.isEmpty(accessAuthUpdateCmd.getEndTime())
			){
				throw new BizException("开始时间或者结束时间不能为空");
			}

			if(accessAuthUpdateCmd.getStartTime().isAfter(accessAuthUpdateCmd.getEndTime())){
				throw new BizException("开始时间必须在结束之前");
			}
		}
	}

	private void checkAccessAuthDateTime(AccessAuth accessAuthCmd, AccessAuth accessAuth) {
		if(!accessAuth.equalsByTime(accessAuthCmd)){
			//根据新的时间和设备进行人员下发
			accessAuthRepository.distributeAccessAuth(accessAuthCmd.getId());
		}

	}
}
